﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Net.Mail;
using System.Net.Security;
using System.IO;
using System.Threading;

namespace DemoMailClient
{
    public partial class Form1 : Form
    {
        List<Attachment> list = new List<Attachment>();
        NetworkStream ns;
        SslStream secureStream;

        public Form1()
        {
            InitializeComponent();
            tPassword.PasswordChar = '*';
            //tServer.Text = "smtp.gmail.com";
            tServer.Text = "pop.gmail.com";
            tPort.Text = "995";//"587";
            tLogin.Text = "kovanjko.oleg@gmail.com";
        }

        private void bSend_Click(object sender, EventArgs e)
        {
            MailAddress fromAddress = new MailAddress(tLogin.Text);
            MailAddress toAddress = new MailAddress(tLogin.Text);

            string subject = "Subject test";
            string body = tBody.Text;
            
            NetworkCredential credentials = new NetworkCredential(fromAddress.Address, tPassword.Text);
            //SmtpClient smtp = new SmtpClient(tServer.Text, int.Parse(tPort.Text));
            SmtpClient smtp = new SmtpClient("smtp.gmail.com", int.Parse(587.ToString()));

            smtp.Credentials = credentials;
            smtp.EnableSsl = true;
            
            MailMessage message = new MailMessage(fromAddress, toAddress);
            //MailMessage message = new MailMessage(new MailAddress("did.moroz@moroz.com", "Did Moroz"), toAddress);
            message.Subject = subject;
            message.Body = body;
            if(list.Count > 0)
                message.Attachments.Add(list[0]);
            try
            {
                smtp.Send(message);
                MessageBox.Show("Message was sent!!!");
            }
            catch (SmtpException ex) {
                MessageBox.Show(ex.Message);
            }
            
        }

        private void bAttach_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            if (dlg.ShowDialog() == DialogResult.OK) {
                tAttach.Text = dlg.FileName;
                list.Add(new Attachment(dlg.FileName));
            }
        }

        void LoginAndRetrieve()
        {
            //http://mail.google.com/support/bin/answer.py?hl=ru&answer=13287
            string response;
            string from = null;
            string subject = null;
            int totmessages;
            TcpClient mailclient;
            try
            {
                mailclient = new TcpClient("pop.gmail.com", 995);
                status.Text = "Connect to server";
            }
            catch (SocketException)
            {
                status.Text = "Unable to connect to server";
                return;
            }
            
            //отримуємо потік для відправки повідомлень на сервер - NetworkStream
            ns = mailclient.GetStream();
           
            secureStream = new SslStream(ns, true);
            secureStream.AuthenticateAsClient("pop.gmail.com");

            StreamReader sr = new StreamReader(secureStream);
            StreamWriter sw = new StreamWriter(secureStream);
            
            response = sr.ReadLine(); //Get opening POP3 banner
            MessageBox.Show("Banner: " + response);

            sw.WriteLine("USER " + tLogin.Text); //Send username
            sw.Flush();
            
            response = sr.ReadLine();
            MessageBox.Show("User: " + response);
            if (response.Substring(0, 4) == "-ERR")
            {
                status.Text = "Unable to log into server";
                return;
            }

            sw.WriteLine("PASS " + tPassword.Text);  //Send password
            sw.Flush();

            try
            {
                response = sr.ReadLine();
                MessageBox.Show("Pass: " + response);
            }
            catch (IOException)
            {
                status.Text = "Unable to log into server";
                return;
            }
            if (response.Substring(0, 3) == "-ER")
            {
                status.Text = "Unable to log into server";
                return;
            }

            sw.WriteLine("STAT"); //Send stat command to get number of messages
            sw.Flush();

            response = sr.ReadLine();
            string[] nummess = response.Split(' ');
            MessageBox.Show(nummess[1]);
            try {
                totmessages = Convert.ToInt32(nummess[1]);
                if (totmessages > 0) {
                    status.Text = "you have " + totmessages + " messages";
                }
                else {
                    status.Text = "You have no messages";
                }

                for (int i = 1; i <= 5/*totmessages*/; i++) {
                    sw.WriteLine("top " + i + " 0"); //read header of each message
                    sw.Flush();
                    response = sr.ReadLine();

                    while (true) {
                        response = sr.ReadLine();
                        //MessageBox.Show("Message: " + response);
                        if (response == ".")
                            break;
                        if (response.Length > 4) {
                            if (response.Substring(0, 5) == "From:")
                                from = response;
                            if (response.Substring(0, 8) == "Subject:")
                                subject = response;
                        }
                    }
                    lMessages.Items.Add(i + "  " + from + "  " + subject);
                    //MessageBox.Show(i + "  " + from + "  " + subject);
                }
            }
            catch { status.Text = "Bad command"; }

        }
        private string GetMessage(int messNumber)
        {
            StreamReader sr = new StreamReader(secureStream);
            StreamWriter sw = new StreamWriter(secureStream);
            sw.WriteLine("retr " + (messNumber + 1)); //Retrieve entire message
            sw.Flush();
            string response = sr.ReadLine();
            MessageBox.Show(response);
            string message = "";
            while (true)
            {
                Encoding e = sr.CurrentEncoding;
                //MessageBox.Show(e.EncodingName);
                response = Encoding.Default.GetString(e.GetBytes(sr.ReadLine()));
                
                MessageBox.Show(response);
                if (response == ".")
                    break;

                message += response + "\r\n";
            }
            return message;
        }
        private void bGetMessage_Click(object sender, EventArgs e)
        {
            LoginAndRetrieve();
        }

        private void lMessages_DoubleClick(object sender, EventArgs e)
        {
            tMessage.Text = GetMessage(lMessages.SelectedIndex);
        }

    }
}
